package loveqq.niceexcel.converter.internal.number;

import cn.hutool.core.util.StrUtil;
import loveqq.niceexcel.annotation.internal.Internal;
import loveqq.niceexcel.converter.CellData;
import loveqq.niceexcel.converter.ConvertContext;
import loveqq.niceexcel.converter.Converter;
import loveqq.niceexcel.util.NumberUtils;
import org.apache.poi.ss.usermodel.CellType;

import java.text.ParseException;

/**
 * @author zhongjh@tsintergy.com
 * @date 2022-08-19
 */
@Internal
public class DoubleStringConverter implements Converter<Double> {
    @Override
    public Class<Double> supportJavaType() {
        return Double.class;
    }

    @Override
    public CellType supportExcelType() {
        return CellType.STRING;
    }

    @Override
    public Double convertToJavaData(CellData<?> cellData, ConvertContext context) throws ParseException {
        String value = cellData.getStringValue();
        return StrUtil.isEmpty(value) ? null : NumberUtils.parseDouble(value, context.getNumberFormat());
    }

    @Override
    public CellData<?> convertToExcelData(Double data, ConvertContext context) {
        String value = (data == null) ? null : NumberUtils.format(data, context.getNumberFormat());
        return new CellData<>(value);
    }
}
